package com.yuneec.droneservice.command;

import com.yuneec.droneservice.model.CameraScanResult;
import com.yuneec.droneservice.request.IResponse;
import com.yuneec.droneservice.utils.ByteUtils;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

/**
 * Created by gjw on 2017/3/27.
 */

public class ScanCamera extends BaseCommand {

    public ScanCamera() {
        super(MAV_RC_COMMAND.MAV_RC_CMD_SCAN_CAMERA);
    }

    @Override
    public IResponse<CameraScanResult[]> toResponse(byte[] data, int off, int payloadLen) {
        int code = data[off + 1] & 0xff;
        IResponse<CameraScanResult[]> response = new IResponse(ids(), code);
        if (code == MAV_RC_ERROR_CODE.MAV_RC_ERR_SUCCESS) {
            int count = data[off + 2];
            if (count > 0) {
                CameraScanResult[] cameras = new CameraScanResult[count];
                int skip = 3;
                for (int i = 0; i < count; i++) {
                    CameraScanResult camera = new CameraScanResult();
                    int len = ByteUtils.byteArrayToShort(Arrays.copyOfRange(data, off + skip, off + skip + 2), IS_BIGENDIAN);
                    try {
                        camera.setSsid(new String(Arrays.copyOfRange(data, off + skip + 2, off + skip + 2 + len), "utf-8"));
                        camera.setFrequency(ByteUtils.byteArrayToShort(Arrays.copyOfRange(data, off + skip + 2 + len, off + skip + 2 + len + 2), IS_BIGENDIAN));
                        camera.setSignalLevel(ByteUtils.byteArrayToShort(Arrays.copyOfRange(data, off + skip + 2 + len + 2, off + skip + 2 + len + 4), IS_BIGENDIAN));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    skip += 6 + len;
                    cameras[i] = camera;
                }
                response.setParam(cameras);
            }
        }
        return response;
    }
}
